package mysql

import (
	"cloud-storage/global"
	"cloud-storage/lib"
	"database/sql"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"log"
	"time"
)

type Model struct {
	ID       int            `json:"id"`
	CreateOn time.Time      `json:"create_on" gorm:"autoCreateTime"`
	UpdateOn time.Time      `json:"update_on" gorm:"autoUpdateTime"`
	DeleteOn gorm.DeletedAt `json:"delete_on" gorm:"index"`
}

func InitMysql() {
	dns := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
		lib.MysqlSetting.UserName,
		lib.MysqlSetting.Password,
		lib.MysqlSetting.Host,
		lib.MysqlSetting.Name,
	)
	db, err := sql.Open("mysql", dns)
	if err != nil {
		log.Fatal(2, err)
	}

	db.SetMaxIdleConns(lib.MysqlSetting.MaxIdleConns)
	db.SetMaxOpenConns(lib.MysqlSetting.MaxOpenConns)

	global.DB, err = gorm.Open(mysql.New(mysql.Config{Conn: db}), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			//设置表明为单数模式
			SingularTable: true,
		},
	})
	if err != nil {
		zap.L().Fatal("init logger failed")
		return
	}
	zap.L().Info("init mysql success")
}

// Close 关闭连接
func Close() {
	db, err := global.DB.DB()
	if err != nil {
		log.Fatal("db close err", err)
	}
	_ = db.Close()
}
